// JWT认证管理
class JWTAuth {
    constructor() {
        this.baseURL = '/api/v1';
        this.accessToken = null;
        this.refreshTokenValue = null;
        this.isRefreshing = false;
        this.refreshPromise = null;
        
        // 初始化时从Cookie获取令牌
        this.loadTokensFromCookies();
        
        // 设置定时刷新
        this.setupAutoRefresh();
    }
    
    // 从Cookie加载令牌
    loadTokensFromCookies() {
        this.accessToken = this.getCookie('access_token');
        this.refreshTokenValue = this.getCookie('refresh_token');
    }
    
    // 获取Cookie
    getCookie(name) {
        const value = `; ${document.cookie}`;
        const parts = value.split(`; ${name}=`);
        if (parts.length === 2) return parts.pop().split(';').shift();
        return null;
    }
    
    // 设置Cookie
    setCookie(name, value, days) {
        const expires = new Date();
        expires.setTime(expires.getTime() + (days * 24 * 60 * 60 * 1000));
        document.cookie = `${name}=${value};expires=${expires.toUTCString()};path=/;SameSite=Lax`;
    }
    
    // 删除Cookie
    deleteCookie(name) {
        document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 UTC;path=/;`;
    }
    
    // 登录
    async login(username, password) {
        try {
            const response = await fetch(`${this.baseURL}/login`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ username, password })
            });
            
            const data = await response.json();
            console.log('登录响应:', data); // 调试日志
            
            if (response.ok && data.success) {
                // 从data.data中获取tokens，data.data是AuthService.create_login_response的返回值
                const loginData = data.data;
                const tokens = loginData.tokens;
                this.accessToken = tokens.access_token;
                this.refreshTokenValue = tokens.refresh_token;
                
                // 更新Cookie
                this.setCookie('access_token', this.accessToken, 1/24); // 30分钟
                this.setCookie('refresh_token', this.refreshTokenValue, 7); // 7天
                
                return { success: true, data: loginData };
            } else {
                return { success: false, error: data.error || data.message || '登录失败' };
            }
        } catch (error) {
            console.error('登录错误:', error);
            return { success: false, error: '网络错误' };
        }
    }
    
    // 注册
    async register(username, password) {
        try {
            const response = await fetch(`${this.baseURL}/register`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ username, password })
            });
            
            const data = await response.json();
            
            if (response.ok && data.success) {
                return { success: true, data };
            } else {
                return { success: false, error: data.error || data.message || '注册失败' };
            }
        } catch (error) {
            console.error('注册错误:', error);
            return { success: false, error: '网络错误' };
        }
    }
    
    // 刷新令牌
    async refreshToken() {
        if (this.isRefreshing) {
            return this.refreshPromise;
        }
        
        this.isRefreshing = true;
        this.refreshPromise = this._doRefreshToken();
        
        try {
            const result = await this.refreshPromise;
            return result;
        } finally {
            this.isRefreshing = false;
            this.refreshPromise = null;
        }
    }
    
    async _doRefreshToken() {
        try {
            const response = await fetch(`${this.baseURL}/refresh`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ refresh_token: this.refreshTokenValue })
            });
            
            const data = await response.json();
            console.log('刷新令牌响应:', data); // 调试日志
            
            if (response.ok && data.success) {
                // 从data.data中获取tokens，data.data是AuthService.create_refresh_response的返回值
                const refreshData = data.data;
                const tokens = refreshData.tokens;
                this.accessToken = tokens.access_token;
                this.refreshTokenValue = tokens.refresh_token;
                this.setCookie('access_token', this.accessToken, 1/24);
                this.setCookie('refresh_token', this.refreshTokenValue, 7);
                return { success: true, data: refreshData };
            } else {
                // 刷新失败，清除所有令牌
                this.logout();
                return { success: false, error: data.error || data.message || '令牌刷新失败' };
            }
        } catch (error) {
            console.error('刷新令牌错误:', error);
            this.logout();
            return { success: false, error: '网络错误' };
        }
    }
    
    // 登出
    async logout() {
        console.log('jwtAuth.logout() 被调用');
        console.log('当前accessToken:', this.accessToken);
        console.log('当前refreshTokenValue:', this.refreshTokenValue);
        
        try {
            // 尝试发送logout请求，即使没有token也要尝试
            console.log('发送logout请求到:', `${this.baseURL}/logout`);
            const response = await fetch(`${this.baseURL}/logout`, {
                method: 'POST',
                headers: {
                    'Authorization': this.accessToken ? `Bearer ${this.accessToken}` : '',
                    'Content-Type': 'application/json',
                }
            });
            console.log('logout响应状态:', response.status);
            console.log('logout响应:', await response.text());
        } catch (error) {
            console.error('登出请求失败:', error);
        } finally {
            // 无论API调用是否成功，都清除本地状态
            console.log('清除本地状态');
            this.accessToken = null;
            this.refreshTokenValue = null;
            this.deleteCookie('access_token');
            this.deleteCookie('refresh_token');
            
            // 重定向到首页
            console.log('跳转到首页');
            window.location.href = '/';
        }
    }
    
    // 验证令牌
    async verifyToken() {
        try {
            const response = await fetch(`${this.baseURL}/verify`, {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${this.accessToken}`,
                }
            });
            
            const data = await response.json();
            return { success: response.ok && data.success, data };
        } catch (error) {
            console.error('验证令牌错误:', error);
            return { success: false, error: '网络错误' };
        }
    }
    
    // 获取用户信息
    async getProfile() {
        try {
            const response = await fetch(`${this.baseURL}/profile`, {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${this.accessToken}`,
                }
            });
            
            const data = await response.json();
            
            if (response.ok && data.success) {
                return { success: true, data };
            } else {
                return { success: false, error: data.error || data.message || '获取用户信息失败' };
            }
        } catch (error) {
            console.error('获取用户信息错误:', error);
            return { success: false, error: '网络错误' };
        }
    }
    
    // 带认证的API请求
    async authenticatedRequest(url, options = {}) {
        console.log('authenticatedRequest被调用，当前accessToken:', this.accessToken ? '存在' : '不存在');
        
        // 重新从cookie加载令牌，以防页面刷新后状态丢失
        this.loadTokensFromCookies();
        console.log('重新加载后accessToken:', this.accessToken ? '存在' : '不存在');
        
        // 如果没有访问令牌，尝试从refresh token获取新的访问令牌
        if (!this.accessToken && this.refreshTokenValue) {
            console.log('没有accessToken但有refreshToken，尝试刷新令牌');
            const refreshResult = await this.refreshToken();
            if (!refreshResult.success) {
                console.log('刷新令牌失败，重定向到登录页');
                window.location.href = '/login';
                return;
            }
        } else if (!this.accessToken && !this.refreshTokenValue) {
            console.log('既没有accessToken也没有refreshToken，重定向到登录页');
            window.location.href = '/login';
            return;
        }
        
        // 添加认证头
        const headers = {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${this.accessToken}`,
            ...options.headers
        };
        
        console.log('发送请求到:', url, '使用token:', this.accessToken ? this.accessToken.substring(0, 20) + '...' : 'null');
        
        try {
            const response = await fetch(url, {
                ...options,
                headers
            });
            
            console.log('请求响应状态:', response.status);
            
            // 如果返回401，尝试刷新令牌
            if (response.status === 401) {
                console.log('收到401错误，尝试刷新令牌');
                const refreshResult = await this.refreshToken();
                if (refreshResult.success) {
                    // 重试请求
                    console.log('刷新成功，重试请求');
                    headers.Authorization = `Bearer ${this.accessToken}`;
                    const retryResponse = await fetch(url, {
                        ...options,
                        headers
                    });
                    return retryResponse;
                } else {
                    // 刷新失败，重定向到登录页
                    console.log('刷新失败，重定向到登录页');
                    window.location.href = '/login';
                    return;
                }
            }
            
            return response;
        } catch (error) {
            console.error('请求错误:', error);
            throw error;
        }
    }
    
    // 设置自动刷新
    setupAutoRefresh() {
        // 每25分钟检查一次令牌（令牌30分钟过期）
        setInterval(async () => {
            if (this.accessToken) {
                console.log('自动检查令牌有效性...');
                const verifyResult = await this.verifyToken();
                if (!verifyResult.success) {
                    console.log('令牌已过期，自动刷新');
                    await this.refreshToken();
                } else {
                    console.log('令牌仍然有效');
                }
            }
        }, 25 * 60 * 1000);
    }
    
    // 检查是否已登录
    isLoggedIn() {
        return !!this.accessToken;
    }
}

// 创建全局实例
const jwtAuth = new JWTAuth();
console.log('jwtAuth对象已创建:', jwtAuth);

// 页面加载时检查登录状态
document.addEventListener('DOMContentLoaded', async () => {
    console.log('DOM加载完成，检查登录状态');
    
    // 重新从cookie加载令牌
    jwtAuth.loadTokensFromCookies();
    console.log('重新加载后accessToken:', jwtAuth.accessToken ? '存在' : '不存在');
    console.log('重新加载后refreshTokenValue:', jwtAuth.refreshTokenValue ? '存在' : '不存在');
    
    // 如果已经有accessToken，说明用户已登录，不需要每次都验证
    // 只有在token过期时（401错误）才会自动刷新
    if (jwtAuth.accessToken) {
        console.log('用户已登录，有accessToken，跳过验证');
        return;
    }
    
    // 如果没有accessToken但有refreshToken，尝试刷新
    if (jwtAuth.refreshTokenValue) {
        console.log('用户未登录，但有refreshToken，尝试刷新');
        const refreshResult = await jwtAuth.refreshToken();
        if (!refreshResult.success) {
            console.log('刷新失败，清除登录状态');
            jwtAuth.logout();
        } else {
            console.log('刷新成功，用户已恢复登录状态');
        }
    } else {
        console.log('用户未登录，也没有refreshToken');
    }
});

// 导出供其他脚本使用
window.jwtAuth = jwtAuth;
console.log('jwtAuth已挂载到window对象'); 